<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';

import {
  getEmpesPage,
  override,
  sDelBinding,
  sbinding,
} from '#/api/moxi/ruleBinding';
import type { RuleBindingAPI } from '#/api/moxi/ruleBinding';
import { getSysAbsenceRulePage } from '#/api/moxi/sysabsencerule';

import { ref, onMounted } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';

import { useGridColumns, useGridFormSchema } from './data';
import DeptTree from './modules/dept-tree.vue';
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

const options = ref<any['options']>([]);
/** 初始化 */
onMounted(async () => {
  let res = await getSysAbsenceRulePage({
    pageNo: 1,
    pageSize: 99,
  });
  if (res.total > 0) {
    res.list.map((item) => {
      options.value.push({
        value: item.id,
        label: item.ruleAlias,
      });
    });
  }
});
/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 选择部门 */
const searchDeptId = ref<number | undefined>(undefined);

async function handleDeptSelect(dept: SystemDeptApi.Dept) {
  searchDeptId.value = dept.deptId;
  onRefresh();
}
const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: RuleBindingAPI.RuleBindingfo[];
}) {
  checkedIds.value = records.map((item) => item.id as number);
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    // columns: useGridColumns(handleStatusChange),
    columns: useGridColumns(),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (searchDeptId.value)
            return await getEmpesPage({
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              deptId: searchDeptId.value,
            });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: { code: 'query' },
      search: true,
    },
  } as VxeTableGridOptions<RuleBindingAPI.RuleBindingfo>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});

// 绑定
const handleChange = async (
  value: number,
  row: RuleBindingAPI.RuleBindingfo,
) => {
  console.log('selected', value, 'row', row);
  try {
    const res = await sbinding({
      ruleId: value,
      userid: row.userid,
    });
    if (res.msg == '成功') {
      message.success('操作成功');
      onRefresh();
    } else {
      message.error(res.msg);
    }
  } catch {
    console.log('操作失败');
  }
};
// 解除绑定
const handleUnbind = async (row: RuleBindingAPI.RuleBindingfo) => {
  try {
    const res = await sDelBinding({
      ruleId: row.ruleId,
      userid: row.userid,
    });
    if (res.msg === '成功') {
      message.success('解绑成功');
      onRefresh();
    } else {
      message.error(res.msg);
    }
  } catch {
    console.log('解绑失败');
  }
};
</script>

<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <ResetPasswordDrawer @success="onRefresh" />
    <AssignRoleDrawer @success="onRefresh" />
    <ImportDrawer @success="onRefresh" />

    <div class="flex h-full w-full">
      <!-- 左侧部门树 -->
      <Card class="mr-4 h-full w-1/6 overflow-auto">
        <DeptTree @select="handleDeptSelect" />
      </Card>
      <!-- 右侧用户列表 -->
      <div class="w-5/6">
        <Grid table-title="用户列表">
          <template #actions="{ row }">
            <a-select
              v-model:value="row.ruleId"
              style="width: 120px"
              :options="options"
              @change="(value) => handleChange(value, row)"
            >
            </a-select>
            <a-button
              type="link"
              danger
              class="ml-2"
              @click="handleUnbind(row)"
            >
              解绑
            </a-button>
          </template>
        </Grid>
      </div>
    </div>
  </Page>
</template>
